import 'package:im_app/im/util/ImConstant.dart';
import 'package:logger/logger.dart';

import '../dao/ImMessageDao.dart';
import '../dao/ImSessionDao.dart';
import '../util/ImCacheFactory.dart';
import '../util/UiUtil.dart';
import 'BaseService.dart';

class CheckHotMessageTotalService extends BaseService {

  final _logger = Logger(printer: PrettyPrinter(),);

  Future<void> checkHotMessageTotal(String userId, DateTime startDate) async {
    var messageDao = ImMessageDao();
    var sessionDao = ImSessionDao();
    var hotMessages = await messageDao.getHotMessageTotal(userId, startDate);
    var sessions = await sessionDao.getByUserIdAndTimeAndSize(userId, startDate, 0, ImConstant.SESSION_MAX_SIZE);

    for (var hotMessageTotal in hotMessages) {
      if (hotMessageTotal.total >= 0) {
        ImCacheFactory.getInstance().setHotMessage(hotMessageTotal.sessionId, hotMessageTotal.total);
      }
    }

    for (var session in sessions) {
      var isHave = false;
      for (var hotMessage in hotMessages) {
        if (hotMessage.sessionId == session.id!) {
          isHave = true;
          if (hotMessage.total != session.hotMessageTotal) {
            _logger.i("session hot message total ${session.id!}, ${hotMessage.total}");
            await sessionDao.setHotMessageNum(session.id!, hotMessage.total);
            continue;
          }
        }
      }
      if (isHave == false && (session.hotMessageTotal??0) > 0) {
        _logger.i("session hot message total 0 ${session.id!}, ${isHave}");
        await sessionDao.setHotMessageNum(session.id!, 0);
      }
    }

    // var hotMessageTotal = hotMessages.map((value)=>value.total).reduce((value, data)=>value+data);
    // UiUtil.uiChangeHotMessage(hotMessageTotal);
  }
}